package com.bigknow.appstore.proxy.handler.lock;

import com.bigknow.appstore.proxy.util.HandlerVariables;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * 删除闭锁
 * Created by chaos on 2016/9/13.
 */
@ChannelHandler.Sharable
public class RemoveAckHandler extends ChannelOutboundHandlerAdapter {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ArrayBlockingQueue queue = HandlerVariables.acks.get(ctx.channel().id().asLongText());
        if(queue!=null&&queue.size()>0) {
            queue.poll();
        }
        ctx.write(msg, promise);
    }

    @Override
    public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise)
            throws Exception {
        clearAck(ctx.channel().id().asLongText());
        ctx.disconnect(promise);
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise)
            throws Exception {
        clearAck(ctx.channel().id().asLongText());
        ctx.close(promise);
    }

    private void clearAck(String channelId){
        ArrayBlockingQueue queue = HandlerVariables.acks.remove(channelId);
        if(queue!=null) queue.clear();
    }
}
